﻿using System;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Xml;

namespace AT.IBMS.Framework.WeiXin
{
    public class WeiXinProviderBase : ProviderBase
    {

        /// <summary>
        /// 验证微信接入信息。
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        public virtual bool CheckSignature(string signature, string timestamp, string nonce)
        {
            string[] arr;
            StringBuilder content;
            string tmpStr;
            bool result;

            content = new StringBuilder();
            arr = new String[] { FrameworkManager.FrameworkConfigurationSettings.WeiXin.Token, timestamp, nonce };

            // 将token、timestamp、nonce三个参数进行字典序排序
            Array.Sort<String>(arr);

            for (int i = 0; i < arr.Length; i++)
            {
                content.Append(arr[i]);
            }

            tmpStr = SHA1_Encrypt(content.ToString());
            result = tmpStr != null ? tmpStr.Equals(signature) : false;

            return result;

        }

        private string SHA1_Encrypt(string Source_String)
        {

            byte[] strRes;
            HashAlgorithm iSHA;
            StringBuilder enText;

            enText = new StringBuilder();
            iSHA = new SHA1CryptoServiceProvider();
            strRes = Encoding.Default.GetBytes(Source_String);

            strRes = iSHA.ComputeHash(strRes);

            foreach (byte iByte in strRes)
            {
                enText.AppendFormat("{0:x2}", iByte);
            }

            return enText.ToString();

        }

        /// <summary>
        /// 解析微信发送来的xml文件。
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public virtual Dictionary<string, string> ParseXml(String xml)
        {

            XmlDocument xmlDocument;
            XmlNode bodyNode;
            Dictionary<string, string> result;

            xmlDocument = new XmlDocument();
            result = new Dictionary<string, string>();

            xmlDocument.LoadXml(xml);
            bodyNode = xmlDocument.ChildNodes[0];

            if (bodyNode.ChildNodes.Count > 0)
            {

                foreach (XmlNode xn in bodyNode.ChildNodes)
                {
                    result.Add(xn.Name.ToUpper(), xn.InnerText);
                }

            }

            return result;

        }

    }
}
